# -*- coding: utf-8 -*-

# 1 导入库
import sys, pygame
from random import randrange
from pygame.locals import KEYDOWN, K_UP, K_RIGHT, K_DOWN, K_LEFT, QUIT, K_r, K_q
from itertools import count



# 2 初始化游戏，设置窗口
pygame.init()
#定义字体样式
clock = pygame.time.Clock()
screen = pygame.display.set_mode(size)
size = width, height = 480, 480
font = pygame.font.Font(None, 14)
# 3 每次移动增或减十个像素
up, right, down, left = (0, -10), (10, 0), (0, 10), (-10, 0)  

#默认蛇头向下，没有食物，死亡等于假
snake_dir, food, dead = down, None, False 
# 4 在屏幕上画出蛇，并定义蛇身长为20
snake = [pygame.Rect(10, 10 + value * 10, 10, 10) for value in range(20)]
# 5 设置背景色和蛇的颜色
foreground, background = (255, 255, 255), (0, 0, 0)
# 6 设置蛇运行的速度，最高不超过30
for counter in count():
    clock.tick(min(5 + (len(snake) / 4), 30))
# 7 事件监听器，不停的获取按下的按键
    event = pygame.event.poll()
# 8 判断被按下的键是关闭按键，则退出程序
    if event.type == QUIT:
        pygame.quit()
        sys.exit()
# 9 判断按键，改变运行方向，但是上下，左右不能逆向改变
    elif event.type == KEYDOWN:
        if event.key == K_UP and snake_dir != down:
            snake_dir = up
        elif event.key == K_RIGHT and snake_dir != left:
            snake_dir = right
        elif event.key == K_DOWN and snake_dir != up:
            snake_dir = down
        elif event.key == K_LEFT and snake_dir != right:
            snake_dir = left
# 10 设置某一按键令游戏重新开始
        elif event.key == K_r:
            snake_dir, food, dead = down, None, False
            snake = [pygame.Rect(10, 10 + value * 10, 10, 10)
                     for value in range(20)]
            foreground, background = (255, 255, 255), (0, 0, 0)
        elif event.key == K_q:
            pygame.event.post(pygame.event.Event(QUIT))
# 11 如果蛇死亡，则终止整个循环
    if dead:
        continue
# 12 当蛇吃到食物时，蛇身长度增加1
    next = snake[-1].move(snake_dir)
# 13 当蛇碰到屏幕在相反侧出现
    if next.left < 0: 
        next.left = width - 10
    if next.left >= width:
        next.left = 0
    if next.top < 0: 
        next.top = height - 10
    if next.top >= height:
        next.top = 0
# 14 如果蛇头碰到蛇身，则蛇死亡，屏幕和蛇的背景颜色互换，否则蛇身长度不变能正常运行
    if next in snake:
        dead = True
        foreground, background = background, foreground
    else:
        snake.append(next)
# 15 如果蛇吃到食物，食物消失，否则每运行一步，删除蛇头
        if next == food:
            food = None

        else:
            del snake[0]
# 16 如果食物为空，并且控制食物出现的时间，随机在屏幕上生成食物（像素10*10）
    if food is None and counter % 50 == 0:
        food = pygame.Rect(randrange(48) * 10, randrange(48) * 10, 10, 10)
# 17 填充屏幕
    screen.fill(background)
# 18 当蛇吃到食物，画蛇身
    for rect in snake:
        pygame.draw.rect(screen, foreground, rect)
# 19 当食物新生成时，在屏幕上画出
    if food:
        pygame.draw.rect(screen, foreground, food)
# 20 在屏幕左上角上显示蛇的长度，并画出
    surface = font.render(str(len(snake)), True, foreground)
    screen.blit(surface, (0, 0))
#刷新屏幕
    pygame.display.flip()
